#!/usr/bin/perl

use Data::Dumper;
use Text::CSV;
use strict;

sub usage {
	print "usage: graph_accuracy.pl <observations_file> <data_file1> <data_file2> <data_file3> ...\n";
	exit 0;
}

my @obsarray;
my @opsarray;
my @output;
my $NUMPOINTS = 20;
my $NUMINC = 100 / $NUMPOINTS;

for (my $argnum = 0; $argnum <= $#ARGV; $argnum++) { 
	open INFILE, "<$ARGV[$argnum]" or die "Cannot open file: $!";

	if (!$argnum) {
		while (<INFILE>) {
			chomp();
			if (/^TEST/) {
				push(@opsarray, "foo");
				push(@obsarray, "t");
			} elsif (/^n\t(OP_[\w_]+)/) {
				push(@opsarray, $1);
				push(@obsarray, "n");
			} elsif (/^y\t(OP_[\w_]+)/) {
				push(@opsarray, $1);
				push(@obsarray, "y");
			} else {
				die "ERROR: Invalid observation file: $_\n";
			}
		}
		push(@output, ["Cutoff"]);
		for (my $j = 0; $j <= $NUMPOINTS; $j++) {
			push(@output, [$j * $NUMINC]);
		}
	} else {
		my @fpar = map { 0 } (0..$NUMPOINTS);
		my @fnar = map { 0 } (0..$NUMPOINTS);
		my $testnum = 0;
		my $totops = 0;
		my $i = 0;
		#print Dumper(\@fpar);
		while (<INFILE>) {
			chomp();
			die if ((($obsarray[$i] eq "t") && (!/^TEST/)) || ((/^TEST/) && (!$obsarray[$i] eq "t")));
			if (/^(OP_\w+): ([\d\.]+)/) {
				my $op = $1;
				my $res = $2;
				$totops++;
				die "op:$op != opsarray[$i]:$opsarray[$i]" if ($op ne $opsarray[$i]);
				for (my $j = 0; $j <= $NUMPOINTS; $j++) {
					if (($res < $j*$NUMINC) && ($obsarray[$i] eq "y")) {
						#if ($j == $NUMPOINTS) {
						#	print "$op: false negative\n";
						#}
						$fnar[$j]++;
					} elsif ((($res > $j*$NUMINC) || (($j == $NUMPOINTS) && ($res == 100))) && ($obsarray[$i] eq "n")) {
						#if ($j == $NUMPOINTS) {
						#	print "$op: false positive\n";
						#}
						$fpar[$j]++;
					} else {
						#if ($j == $NUMPOINTS) {
						#	print "$op: OK\n";
						#}
					}
				}
			} elsif (/^TEST/) {
				$testnum++;
				#print "TEST $testnum\n";
			} else {
				print "ERROR: $_\n";
				die "$_";
			}
			$i++;
		}
		unshift(@fpar, $ARGV[$argnum] . "-FP");
		unshift(@fnar, $ARGV[$argnum] . "-FN");
		die "Output: $#output, FPAR $#fpar" if ($#output != $#fpar);
		for (my $j = 0; $j <= $#output; $j++) {
			if (!$j) {
				push(@{@output[$j]}, $fpar[$j], $fnar[$j]);
			} else {
				push(@{@output[$j]}, ($fpar[$j]/$totops)*100, ($fnar[$j]/$totops)*100);
			}
		}
		#print "Output: " . Dumper(\@output) . "\n";
	}

	close(INFILE);
}

shift(@ARGV);
#print join(",", "Cutoff", map { ($_ . "-FP", $_ . "-FN") } (@ARGV)) . "\n";

my $csv = Text::CSV->new();

foreach (@output) {
	die if (!$csv->combine(@$_));
	print $csv->string() . "\n";
}
